package gdufs.lkl.calculator;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

/**
 * 科学计算器Activity
 * 支持基本运算、科学函数、存储器功能以及角度/弧度切换
 */
public class ScientificCalculatorActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "ScientificCalculator";

    // UI元素
    private TextView tvExpression;
    private TextView tvResult;

    // 计算器状态
    private StringBuilder currentInput = new StringBuilder();
    private StringBuilder expression = new StringBuilder();
    private boolean lastInputWasOperator = false;
    private boolean lastInputWasEquals = false;
    private boolean isInRadianMode = true; // 默认使用弧度制
    private boolean isSecondFunction = false; // 第二功能模式
    private boolean isInErrorState = false; // 是否处于错误状态    // 计算引擎实例
    private CalculationEngine calculationEngine;

    // 历史记录管理器
    private CalculationHistory calculationHistory;

    // 设置管理器
    private SettingsManager settingsManager;

    // 存储器
    private double memoryValue = 0;

    private static final int REQUEST_CODE_HISTORY = 100;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); // 强制横屏
        setContentView(R.layout.activity_scientific_calculator);        // 设置工具栏
        setSupportActionBar(findViewById(R.id.toolbar));
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }        // 初始化UI元素
        tvExpression = findViewById(R.id.tvExpression);
        tvResult = findViewById(R.id.tvResult);

        // 初始化设置管理器
        settingsManager = SettingsManager.getInstance(this);

        // 初始化计算引擎
        calculationEngine = CalculationEngine.getInstance();

        // 初始化历史记录管理器
        calculationHistory = CalculationHistory.getInstance(this);

        // 处理从历史记录传来的数据
        handleIntentData();

        // 设置数字按钮的点击监听器
        findViewById(R.id.btn0).setOnClickListener(this);
        findViewById(R.id.btn1).setOnClickListener(this);
        findViewById(R.id.btn2).setOnClickListener(this);
        findViewById(R.id.btn3).setOnClickListener(this);
        findViewById(R.id.btn4).setOnClickListener(this);
        findViewById(R.id.btn5).setOnClickListener(this);
        findViewById(R.id.btn6).setOnClickListener(this);
        findViewById(R.id.btn7).setOnClickListener(this);
        findViewById(R.id.btn8).setOnClickListener(this);
        findViewById(R.id.btn9).setOnClickListener(this);

        // 设置操作符按钮的点击监听器
        findViewById(R.id.btnPlus).setOnClickListener(this);
        findViewById(R.id.btnMinus).setOnClickListener(this);
        findViewById(R.id.btnMultiply).setOnClickListener(this);
        findViewById(R.id.btnDivide).setOnClickListener(this);
        findViewById(R.id.btnEquals).setOnClickListener(this);
        findViewById(R.id.btnDot).setOnClickListener(this);
        findViewById(R.id.btnChangeSign).setOnClickListener(this);
        findViewById(R.id.btnClear).setOnClickListener(this);
        findViewById(R.id.btnBackspace).setOnClickListener(this);
        findViewById(R.id.btnPercent).setOnClickListener(this);

        // 设置括号按钮的点击监听器
        findViewById(R.id.btnLeftBracket).setOnClickListener(this);
        findViewById(R.id.btnRightBracket).setOnClickListener(this);

        // 设置科学计算功能按钮的点击监听器
        findViewById(R.id.btn2nd).setOnClickListener(this);
        findViewById(R.id.btnSin).setOnClickListener(this);
        findViewById(R.id.btnCos).setOnClickListener(this);
        findViewById(R.id.btnTan).setOnClickListener(this);
        findViewById(R.id.btnSinh).setOnClickListener(this);
        findViewById(R.id.btnCosh).setOnClickListener(this);
        findViewById(R.id.btnTanh).setOnClickListener(this);
        findViewById(R.id.btnLn).setOnClickListener(this);
        findViewById(R.id.btnLog).setOnClickListener(this);
        findViewById(R.id.btnSqrt).setOnClickListener(this);
        findViewById(R.id.btnCbrt).setOnClickListener(this);
        findViewById(R.id.btnSquare).setOnClickListener(this);
        findViewById(R.id.btnCube).setOnClickListener(this);
        findViewById(R.id.btnPowerY).setOnClickListener(this);
        findViewById(R.id.btnPower10).setOnClickListener(this);
        findViewById(R.id.btnExp).setOnClickListener(this);
        findViewById(R.id.btnFactorial).setOnClickListener(this);
        findViewById(R.id.btnReciprocal).setOnClickListener(this);
        findViewById(R.id.btnPi).setOnClickListener(this);
        findViewById(R.id.btnE).setOnClickListener(this);
        findViewById(R.id.btnRad).setOnClickListener(this);
        findViewById(R.id.btnRandom).setOnClickListener(this);

        // 设置存储器按钮的点击监听器
        findViewById(R.id.btnMC).setOnClickListener(this);
        findViewById(R.id.btnMR).setOnClickListener(this);
        findViewById(R.id.btnMPlus).setOnClickListener(this);
        findViewById(R.id.btnMMinus).setOnClickListener(this);

        // 更新角度模式显示
        updateAngleModeDisplay();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_menu, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            finish();
            return true;
        } else if (id == R.id.action_switch_to_calculator) {
            finish(); // 返回主计算器
            return true;
        } else if (id == R.id.action_switch_to_scientific) {
            // 已经在科学计算器，不操作
            return true;
        } else if (id == R.id.action_switch_to_converter) {
            Intent intent = new Intent(this, ConverterActivity.class);
            startActivity(intent);
            finish(); // 关闭当前活动
            return true;
        } else if (id == R.id.action_custom_function) {
            Intent intent = new Intent(this, CustomFunctionManagerActivity.class);
            startActivity(intent);
            return true;
        } else if (id == R.id.action_history) {
            showHistory();
            return true;
        } else if (id == R.id.action_settings) {
            Intent intent = new Intent(this, SettingsActivity.class);
            startActivity(intent);
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * 使用计算引擎计算表达式
     */
    private double evaluateExpression(String expr) throws Exception {
        return calculationEngine.evaluateExpression(expr, isInRadianMode);
    }

    /**
     * 切换角度/弧度模式
     */
    private void toggleAngleMode() {
        isInRadianMode = !isInRadianMode;
        updateAngleModeDisplay();
        Toast.makeText(this, isInRadianMode ? "弧度制模式" : "角度制模式", Toast.LENGTH_SHORT).show();
    }

    /**
     * 更新角度模式显示
     */
    private void updateAngleModeDisplay() {
        Button btnRad = findViewById(R.id.btnRad);
        if (isInRadianMode) {
            btnRad.setText(R.string.angle_mode_rad);
        } else {
            btnRad.setText(R.string.angle_mode_deg);
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();

        // 数字按钮
        if (id == R.id.btn0) handleNumberInput("0");
        else if (id == R.id.btn1) handleNumberInput("1");
        else if (id == R.id.btn2) handleNumberInput("2");
        else if (id == R.id.btn3) handleNumberInput("3");
        else if (id == R.id.btn4) handleNumberInput("4");
        else if (id == R.id.btn5) handleNumberInput("5");
        else if (id == R.id.btn6) handleNumberInput("6");
        else if (id == R.id.btn7) handleNumberInput("7");
        else if (id == R.id.btn8) handleNumberInput("8");
        else if (id == R.id.btn9) handleNumberInput("9");
        else if (id == R.id.btnDot) handleNumberInput(".");

            // 操作符按钮
        else if (id == R.id.btnPlus) handleOperator("+");
        else if (id == R.id.btnMinus) handleOperator("-");
        else if (id == R.id.btnMultiply) handleOperator("*");
        else if (id == R.id.btnDivide) handleOperator("/");
        else if (id == R.id.btnPercent) handleOperator("%");
        else if (id == R.id.btnPowerY) handleOperator("^");

            // 括号按钮
        else if (id == R.id.btnLeftBracket) handleSpecialFunction("(");
        else if (id == R.id.btnRightBracket) handleSpecialFunction(")");

            // 常量按钮
        else if (id == R.id.btnPi) handleSpecialFunction("π");
        else if (id == R.id.btnE) handleSpecialFunction("e");

            // 功能按钮
        else if (id == R.id.btnEquals) calculateResult();
        else if (id == R.id.btnClear) clearAll();
        else if (id == R.id.btnBackspace) handleBackspace();
        else if (id == R.id.btnChangeSign) changeSign();
        else if (id == R.id.btn2nd) toggleSecondFunction();
        else if (id == R.id.btnRad) toggleAngleMode();

            // 科学计算函数
        else if (id == R.id.btnSin) {
            if (isSecondFunction) {
                handleFunction("asin");  // arcsin
            } else {
                handleFunction("sin");
            }
        } else if (id == R.id.btnCos) {
            if (isSecondFunction) {
                handleFunction("acos");  // arccos
            } else {
                handleFunction("cos");
            }
        } else if (id == R.id.btnTan) {
            if (isSecondFunction) {
                handleFunction("atan");  // arctan
            } else {
                handleFunction("tan");
            }
        } else if (id == R.id.btnSinh) handleFunction("sinh");
        else if (id == R.id.btnCosh) handleFunction("cosh");
        else if (id == R.id.btnTanh) handleFunction("tanh");
        else if (id == R.id.btnLog) handleFunction("log");
        else if (id == R.id.btnLn) handleFunction("ln");
        else if (id == R.id.btnSqrt) handleFunction("sqrt");
        else if (id == R.id.btnCbrt) handleFunction("cbrt");
        else if (id == R.id.btnSquare) handlePower(2);
        else if (id == R.id.btnCube) handlePower(3);
        else if (id == R.id.btnPower10) handleFunction("10^");
        else if (id == R.id.btnExp) handleFunction("exp");
        else if (id == R.id.btnFactorial) handleFunction("factorial");
        else if (id == R.id.btnReciprocal) handleFunction("1/");
        else if (id == R.id.btnRandom) handleFunction("random");

            // 存储器按钮
        else if (id == R.id.btnMC) handleMemoryClear();
        else if (id == R.id.btnMR) handleMemoryRecall();
        else if (id == R.id.btnMPlus) handleMemoryAdd();
        else if (id == R.id.btnMMinus) handleMemorySubtract();
    }

    /**
     * 处理数字输入
     */
    private void handleNumberInput(String digit) {
        if (lastInputWasEquals || isInErrorState) {
            currentInput.setLength(0);
            expression.setLength(0);
            lastInputWasEquals = false;
            isInErrorState = false;
            tvResult.setText("0"); // 清除错误显示
        }

        currentInput.append(digit);
        lastInputWasOperator = false;
        updateDisplay();
    }

    /**
     * 处理运算符输入
     */
    private void handleOperator(String operator) {
        // 如果处于错误状态，先清除错误
        if (isInErrorState) {
            expression.setLength(0);
            currentInput.setLength(0);
            isInErrorState = false;
            expression.append("0"); // 从0开始新的计算
        }

        if (currentInput.length() > 0) {
            expression.append(currentInput);
            currentInput.setLength(0);
        } else if (expression.length() == 0) {
            // 如果表达式为空且没有当前输入，添加0
            expression.append("0");
        } else if (lastInputWasOperator) {
            // 如果上一个输入也是运算符，则替换它
            expression.deleteCharAt(expression.length() - 1);
        }

        expression.append(operator);
        lastInputWasOperator = true;
        lastInputWasEquals = false;
        updateDisplay();
    }

    /**
     * 处理特殊函数和符号
     */
    private void handleSpecialFunction(String symbol) {
        if (lastInputWasEquals || isInErrorState) {
            expression.setLength(0);
            lastInputWasEquals = false;
            isInErrorState = false;
        }

        if (currentInput.length() > 0) {
            expression.append(currentInput);
            currentInput.setLength(0);
        }

        expression.append(symbol);
        lastInputWasOperator = false;
        updateDisplay();
    }

    /**
     * 处理函数
     */
    private void handleFunction(String funcName) {
        if (lastInputWasEquals || isInErrorState) {
            expression.setLength(0);
            lastInputWasEquals = false;
            isInErrorState = false;
        }

        // 根据函数类型不同处理
        switch (funcName) {
            case "sqrt":
                if (currentInput.length() > 0) {
                    expression.append("sqrt(").append(currentInput).append(")");
                    currentInput.setLength(0);
                } else {
                    expression.append("sqrt(");
                }
                break;

            case "cbrt":
                if (currentInput.length() > 0) {
                    expression.append("cbrt(").append(currentInput).append(")");
                    currentInput.setLength(0);
                } else {
                    expression.append("cbrt(");
                }
                break;

            case "factorial":
                if (currentInput.length() > 0) {
                    expression.append("factorial(").append(currentInput).append(")");
                    currentInput.setLength(0);
                } else {
                    expression.append("factorial(");
                }
                break;

            case "10^":
                if (currentInput.length() > 0) {
                    expression.append("10^").append(currentInput);
                    currentInput.setLength(0);
                } else {
                    expression.append("10^");
                }
                break;

            case "1/":
                if (currentInput.length() > 0) {
                    expression.append("1/").append(currentInput);
                    currentInput.setLength(0);
                } else {
                    expression.append("1/");
                }
                break;

            case "random":
                expression.append("random()");
                break;
            default:
                // sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, log, ln, exp
                if (currentInput.length() > 0) {
                    expression.append(funcName).append("(").append(currentInput).append(")");
                    currentInput.setLength(0);
                } else {
                    expression.append(funcName).append("(");
                }
                break;
        }

        lastInputWasOperator = false;
        updateDisplay();
    }

    /**
     * 处理幂运算
     */
    private void handlePower(int power) {
        if (currentInput.length() > 0) {
            expression.append("(").append(currentInput).append(")^").append(power);
            currentInput.setLength(0);
        } else if (expression.length() > 0) {
            // 如果当前没有输入但表达式非空，尝试给最后一个数或括号表达式添加幂
            expression.append("^").append(power);
        }

        lastInputWasOperator = false;
        lastInputWasEquals = false;
        updateDisplay();
    }

    /**
     * 计算结果
     */
    private void calculateResult() {
        if (expression.length() == 0 && currentInput.length() == 0) {
            return; // 没有表达式可计算
        }

        StringBuilder fullExpression = new StringBuilder(expression);
        if (currentInput.length() > 0) {
            fullExpression.append(currentInput);
        }
        try {
            // 直接使用计算引擎计算表达式
            double result = evaluateExpression(fullExpression.toString());            // 使用计算引擎格式化结果（使用设置中的小数位数）
            String resultStr = calculationEngine.formatResult(result, settingsManager.getDecimalPlaces());

            // 保存到历史记录
            calculationHistory.addHistory(fullExpression.toString(), resultStr, "scientific");

            // 更新UI
            tvResult.setText(resultStr);
            expression.setLength(0);
            currentInput.setLength(0);
            currentInput.append(resultStr);

            lastInputWasEquals = true;
            lastInputWasOperator = false;
            updateDisplay();
        } catch (Exception e) {
            Toast.makeText(this, "计算错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            tvResult.setText("错误");

            // 清空表达式和当前输入，避免错误状态影响下次计算
            expression.setLength(0);
            currentInput.setLength(0);
            lastInputWasEquals = false;
            lastInputWasOperator = false;
            isInErrorState = true; // 设置错误状态
            updateDisplay();
        }
    }

    /**
     * 清空所有输入和表达式
     */
    private void clearAll() {
        currentInput.setLength(0);
        expression.setLength(0);
        lastInputWasOperator = false;
        lastInputWasEquals = false;
        isInErrorState = false;
        updateDisplay();
    }

    /**
     * 回退一个字符
     */
    private void handleBackspace() {
        if (currentInput.length() > 0) {
            currentInput.deleteCharAt(currentInput.length() - 1);
            updateDisplay();
        } else if (expression.length() > 0) {
            // 如果删除了函数名或其他特殊字符，可能需要更复杂的处理
            expression.deleteCharAt(expression.length() - 1);
            updateDisplay();
        }
    }

    /**
     * 改变当前输入的正负号
     */
    private void changeSign() {
        if (currentInput.length() > 0) {
            if (currentInput.charAt(0) == '-') {
                currentInput.deleteCharAt(0);
            } else {
                currentInput.insert(0, '-');
            }
            updateDisplay();
        }
    }

    /**
     * 切换第二功能（用于三角函数的反函数）
     */
    private void toggleSecondFunction() {
        isSecondFunction = !isSecondFunction;
        Button btn2nd = findViewById(R.id.btn2nd);
        btn2nd.setSelected(isSecondFunction);

        // 更新按钮文字以显示当前功能
        Button btnSin = findViewById(R.id.btnSin);
        Button btnCos = findViewById(R.id.btnCos);
        Button btnTan = findViewById(R.id.btnTan);

        if (isSecondFunction) {
            btnSin.setText("asin");
            btnCos.setText("acos");
            btnTan.setText("atan");
        } else {
            btnSin.setText("sin");
            btnCos.setText("cos");
            btnTan.setText("tan");
        }

        Toast.makeText(this, isSecondFunction ? "第二功能已开启" : "第二功能已关闭", Toast.LENGTH_SHORT).show();
    }

    /**
     * 更新显示
     */
    private void updateDisplay() {
        tvExpression.setText(expression.toString());
        tvResult.setText(currentInput.length() > 0 ? currentInput.toString() : "0");
    }

    // 存储器功能

    /**
     * 清除存储器
     */
    private void handleMemoryClear() {
        memoryValue = 0;
        Toast.makeText(this, "存储器已清除", Toast.LENGTH_SHORT).show();
    }

    /**
     * 调用存储器值
     */
    private void handleMemoryRecall() {
        currentInput.setLength(0);
        currentInput.append(String.valueOf(memoryValue));
        updateDisplay();
    }

    /**
     * 向存储器添加当前值
     */
    private void handleMemoryAdd() {
        if (currentInput.length() > 0) {
            try {
                double value = Double.parseDouble(currentInput.toString());
                memoryValue += value;
                Toast.makeText(this, "已添加至存储器", Toast.LENGTH_SHORT).show();
            } catch (NumberFormatException e) {
                Toast.makeText(this, "无效的数字格式", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 从存储器减去当前值
     */
    private void handleMemorySubtract() {
        if (currentInput.length() > 0) {
            try {
                double value = Double.parseDouble(currentInput.toString());
                memoryValue -= value;
                Toast.makeText(this, "已从存储器中减去", Toast.LENGTH_SHORT).show();
            } catch (NumberFormatException e) {
                Toast.makeText(this, "无效的数字格式", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 显示历史记录
     */
    private void showHistory() {
        Intent intent = new Intent(this, HistoryActivity.class);
        startActivity(intent);
    }

    /**
     * 处理从历史记录传来的Intent数据
     */
    private void handleIntentData() {
        Intent intent = getIntent();
        if (intent != null) {
            String selectedExpression = intent.getStringExtra(HistoryActivity.EXTRA_SELECTED_EXPRESSION);
            String selectedResult = intent.getStringExtra(HistoryActivity.EXTRA_SELECTED_RESULT);

            if (selectedExpression != null) {
                // 复用表达式
                clearAll();
                expression.append(selectedExpression);
                updateDisplay();
            } else if (selectedResult != null) {
                // 复用结果
                clearAll();
                currentInput.append(selectedResult);
                updateDisplay();
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntentData();
    }
}

